﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using MammothMicro.SMTPGuard;
using MammothMicro.SMTPGuard.Filter;
using MammothMicro.SmtpGuardFilter.Common;

namespace MammothMicro.SmtpGuardFilter.Filter
{
    /// <summary>
    /// Checks email against blocked IP list
    /// </summary>
    public class BlockedIpListFilter : IEmailFilter
    {
        private List<string> _list = new List<string>();

        public bool Accept(MailMessage message)
        {
            if (CheckSingleIp(message) || CheckClassC(message) )
            {
                var msg = new SerializableMailMessage()
                              {Email = message, Id = new Guid(), FilteredBy = Tools.Filters.BlockedIpListFilter};
                
                FilterManager.MailStore.Save(msg);
                return false;
            }
         
            return true;
          
        }

        public void Reload()
        {
            var path = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            path = path.Remove(0, 6);
            var reader = new StreamReader(path + @"\configuration\blockedIpList.txt");
            var text = reader.ReadToEnd().ToLower();
            reader.Close();
            const string delimiter = "\r\n";
            var t = text.Split(delimiter.ToCharArray());
            _list = t.ToList();
        }

        private bool CheckSingleIp(MailMessage message)
        {
            var ips = Tools.ExtractIp(message);
            foreach (var ip in ips)
            {
                if (_list.Exists(p => p == ip.ToString()))
                    return true;
            }
            return false ;
        }

        private bool CheckClassC(MailMessage message)
        {
            var ips = Tools.ExtractIp(message);
            const string delimiter = ".";
            foreach (var ip in ips)
            {
                var t = ip.ToString().Split(delimiter.ToCharArray());
                t[3] = "0";
                if (_list.Exists(p => p == t.ToString()))
                    return true;
            }
           
            return false;
        }
    }
}